#!usr/bin/env python
# -*- coding: utf-8 -*-
import re
import logging
import random
from werkzeug import security
from flask import flash as flask_flash, url_for, current_app
from math import ceil

from fx.lib.crypto import IdCipher
from fx.utils.timeutil import get_now_str


MOBILE_NUM_RE = r'(^1)([35]\d|47|[78][012356789])(\d{8}$)'  # 验证手机号正则
NUMBER_LIST = ["0","1","2","3","4","5","6","7","8","9"]

crypto_key = '!z@s%l^a&wyer'  # 加密key
id_cipher = IdCipher(crypto_key)
id_encrypt = id_cipher.encrypt
id_decrypt = id_cipher.decrypt

def get_default_logger():
    logger = logging.getLogger("jy")
    return logger

logger = get_default_logger()

URL_RE = r'^(?:http)s?://' \
         r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' \
         r'localhost|' \
         r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' \
         r'(?::\d+)' \
         r'?(?:/?|[/?]\S+)$'


def check_url(url):
    regex = re.compile(URL_RE, re.IGNORECASE)
    if regex.match(url):
        return True
    return False


def flash(message, level='info', category='message'):
    flask_flash({'msg': message, 'level': level}, category=category)


class Pagination(object):

    def __init__(self, page, per_page, total_count, endpoint=None, params=None):
        self.params = params
        self.endpoint = endpoint
        self.page = page
        self.per_page = per_page
        self.total_count = total_count

    @property
    def pages(self):
        return int(ceil(self.total_count / float(self.per_page)))

    @property
    def has_prev(self):
        return self.page > 1

    @property
    def has_next(self):
        return self.page < self.pages

    def iter_pages(self, left_edge=2, left_current=2,
                   right_current=5, right_edge=2):
        last = 0
        for num in xrange(1, self.pages + 1):
            if num <= left_edge or \
                (num > self.page - left_current - 1 and
                 num < self.page + right_current) or \
                    num > self.pages - right_edge:
                if last + 1 != num:
                    yield None
                yield num
                last = num


def create_password(raw):
    password = '%s%s' % (raw, current_app.config['PASSWORD_SECRET'])
    return security.generate_password_hash(password)


def check_password(raw, user_password):
        pass_check = '%s%s' % (raw, current_app.config['PASSWORD_SECRET'])
        return security.check_password_hash(user_password, pass_check)

def generate_sn():
    time = get_now_str(format_str='%Y%m%d%H%M%S')
    fix = []
    for i in range(11):
        fix += random.sample(NUMBER_LIST, 1)
    return time + ''.join(fix)